#include "eventtab.h"
#include <QtWidgets/QMessageBox>
#include <QtCore/QString>
#include <QtCore/QList>
#include <QtWidgets/QScrollBar>
#include <QtWidgets/QGridLayout>

EventTab::EventTab(QWidget *parent) :
  QWidget(parent)
{
  listener = new EventListener();
  listenerThread = new QThread(this);

  connect(listenerThread, SIGNAL(started()), listener, SLOT(init()));
  connect(listenerThread, SIGNAL(finished()), listener, SLOT(done()));
  connect(listener, SIGNAL(parsedEventData(QList<Zone>)), this, SLOT(refresh(QList<Zone>)));
  listener->moveToThread(listenerThread);

  mainLayout = new QVBoxLayout(this);
  mainLayout->setMargin(10);

  listenerStatus = new QLabel(tr("Not listening."), this);
  listenerStatus->setAlignment(Qt::AlignCenter);

  eventDisplayer = new QScrollArea(this);
  eventDisplayer->setWidget(new QWidget);
  eventDisplayer->setWidgetResizable(true);

  mainLayout->addSpacing(10);
  mainLayout->addWidget(listenerStatus);
  mainLayout->addSpacing(10);
  mainLayout->addWidget(eventDisplayer);
}

EventTab::~EventTab()
{
  listenerThread->quit();
  listenerThread->wait();
  listener->deleteLater();
}

void EventTab::listenToIt(Shard s)
{
  listener->setShard(s);
  listenerThread->start();
  listenerStatus->setText(tr("Listening: ") + "[" + s.regionShortName() + "] " + s.shardName());
  emit listening(s);
}

void EventTab::stopListening()
{
  listenerThread->quit();
  listenerStatus->setText(tr("Not listening."));
  eventDisplayer->setWidget(new QWidget);
  emit stopping();
}

void EventTab::refresh(const QList<Zone> &list)
{
  int dx = eventDisplayer->verticalScrollBar()->value();
  QWidget* wid = new QWidget;
  QGridLayout* gridLayout = new QGridLayout(wid);

  ZoneWidget* ptr;
  int j = 0;
  for(QList<Zone>::const_iterator i = list.constBegin(); i != list.constEnd(); i++)
    {
      ptr = new ZoneWidget(*i);
      ptr->setParent(wid);
      gridLayout->addWidget(ptr, j / 2, j % 2);
      j++;
    }

  wid->setLayout(gridLayout);
  eventDisplayer->setWidget(wid);
  eventDisplayer->verticalScrollBar()->setValue(dx);
}
